/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gr.anagnosg.ocr.jocrtools;

import gr.anagnosg.general.utils.FileNameContainsFilter;
import gr.anagnosg.general.utils.FileUtils;
import gr.anagnosg.general.utils.ImageUtils;
import static gr.anagnosg.general.utils.ImageUtils.convertImage;
import static gr.anagnosg.general.utils.ImageUtils.unpaperPages;
import gr.anagnosg.general.utils.Ocr;
import gr.anagnosg.general.utils.StringUtils;
import gr.anagnosg.general.utils.diff_match_patch;
import gr.anagnosg.general.utils.text.TextCompare;
import gr.anagnosg.general.utils.text.TextCorrection;
import gr.anagnosg.general.utils.text.Word;
import gr.anagnosg.general.utils.text.WordList;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author anagnosg
 */
public class JocrTools {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception{
        // TODO code application logic here
        JocrTools.ocrTrain("/home/anagnosg/Documents/ocr/train18/2.tif");
        //JocrTools.correctBox("/home/anagnosg/Documents/ocr/train17/1.tif");
    }
    
    public static void deleteTxtFiles(String dir){
        FileNameContainsFilter filter = new FileNameContainsFilter(".txt");
        File[] before = new File(dir).listFiles(filter);
        FileUtils.deleteFiles(before );
    }
    
    public static void correctBox(String inputFilename) throws IOException{//testing function for skipping image convert.
        File fin = new File(inputFilename);
        String path = fin.getParent()+File.separatorChar;
        String fInputFilenameNoExt= FileUtils.getFilenameNoExt(fin);
        String filenameCon = path+"s"+fInputFilenameNoExt+"_all.txt";
        String s1=FileUtils.readTextFile(filenameCon);
        s1 = StringUtils.trimMultiSpace(s1);
            String sourceFile = FileUtils.getFilenameNoExt(new File(inputFilename))+".in";
            String s2=FileUtils.readTextFile(fin.getParent()+File.separatorChar+sourceFile);
            //sugkrisi.
            TextCompare tco =  new TextCompare();
            tco.compare(s1,s2);
            /*int resultOfCompare = tco.getCompareResult();
            if(resultOfCompare==0){//einai ola ida. 

            }*/
            WordList wl1 = tco.getWl1();
            WordList wl2 = tco.getWl2();
            boolean hasEmptyWords1 = wl1.existsEmptyWord();
            boolean hasEmptyWords2 = wl2.existsEmptyWord();
            System.out.println("hasEmptyWords1"+hasEmptyWords1+",hasEmptyWords2"+hasEmptyWords2);
            List diffWords = tco.findWordsDiff(true);
            
            HashMap hmCorrection = TextCorrection.textActions2Correct(tco);
            int correctionResult = (Integer)hmCorrection.get("result");
            if(correctionResult==0){//mporo na sunexiso me thn ekpaideush. den exei diafores

            }
            else if(correctionResult==1){// dhmioyrgia toy box file kai meta dior8osh tou me bash to source automata.
                //to box file 8a ginei me to multi page tiff.
                //File fin = new File(inputFilename);
                //String prefix =fin.getParent()+File.pathSeparatorChar;
                String lang  ="ell.";
                String font = "deja.";
                //exp0.tif
                int numberOfIndex = 0;
                String fileForBox = path+lang+font+"exp"+numberOfIndex+".tif";
                FileUtils.copyfiles(inputFilename, fileForBox) ;//renameTo(new File(fileForBox));
                String boxFileName = TesseractUtils.createBoxFile(fileForBox);
                //read boxfile  
                //String boxFileNameWithNoBox = new File(inputFilename).getParent()+File.separatorChar+FileUtils.getFilenameNoExt(new File(inputFilename));
                List boxData  = TesseractUtils.readBoxFile(boxFileName);
                
                tco.findCharDiff();//find char diffs.
                //correct box file.
                for(int i = 0 ; i < tco.getCharListDiffs().size();i++){
                    Word wT = (Word)tco.getCharListDiffs().get(i);
                    int position  = wT.getStartIndex();
                    System.out.println("box correct p:"+position+",oldText:"+wT.getOldText()+",newText:"+wT.getText());
                    ((String[])boxData.get(position))[0]=wT.getText();
                }
                TesseractUtils.saveBoxFile(boxFileName+"new", boxData);
            }
    
    }
    
    public static void ocrTrain(String inputFilename) throws Exception {
        //check if file is good for train (has only greek letters).
        File fin = new File(inputFilename);
        String path = fin.getParent()+File.separatorChar;
        String sourceFileCheckIfGood = path+FileUtils.getFilenameNoExt(new File(inputFilename))+".in";
        String s1Check=FileUtils.readTextFile(sourceFileCheckIfGood);
        List hasLatin = StringUtils.textHasLatinChars(s1Check);
        if(hasLatin.size()==0){//is ok 
        
            deleteTxtFiles(new File(inputFilename).getParent());
            File fTemp = new File(inputFilename);
            //String inputFilename = "/home/anagnosg/Documents/ocr/train15/1.tif";
            String outputFilename = fTemp.getParent()+File.separatorChar+"s"+FileUtils.getFilenameNoExt(fTemp)+"_p%d.tif";// "/home/anagnosg/Documents/ocr/train15/s1%d.tif ";
            HashMap data = ImageUtils.splitMultiPageTiff( inputFilename, outputFilename,true);
            File f[] = (File[])data.get("files");
            HashMap data2 = ImageUtils.convert2pgm(f);
            File  f2[]=(File[])data2.get("files");
            //HashMap data3= unpaperPages(f2);
            //File  f3[]=(File[])data3.get("files");
            HashMap data4 = convertImage(f2,"tif");
            File  f4[]=(File[])data4.get("files");
            HashMap data5 = Ocr.recognize(f4," -l ell");
            File f5[] = (File[])data5.get("files");
            //sunnenosh ton arxeion se ekan keimeno. 
            String filenameCon = FileUtils.concatTextFileArray(f5);
            //System.out.println("filenameCon"+filenameCon);

            String s1=FileUtils.readTextFile(filenameCon);
            s1 = StringUtils.trimMultiSpace(s1);
            String sourceFile = FileUtils.getFilenameNoExt(new File(inputFilename))+".in";
            String s2=FileUtils.readTextFile(fTemp.getParent()+File.separatorChar+sourceFile);
            s2 = StringUtils.trimMultiSpace(s2);            
            //sugkrisi.
            TextCompare tco =  new TextCompare();
            tco.compare(s1,s2);
            /*int resultOfCompare = tco.getCompareResult();
            if(resultOfCompare==0){//einai ola ida. 

            }*/
            List diffWords = tco.findWordsDiff(true);
            HashMap hmCorrection = TextCorrection.textActions2Correct(tco);
            int correctionResult = (Integer)hmCorrection.get("result");
            if(correctionResult==0){//mporo na sunexiso me thn ekpaideush. den exei diafores

            }
            else if(correctionResult==1){// dhmioyrgia toy box file kai meta dior8osh tou me bash to source automata.
                //to box file 8a ginei me to multi page tiff.
                //File fin = new File(inputFilename);
                //String prefix =fin.getParent()+File.pathSeparatorChar;
                String lang  ="ell.";
                String font = "deja.";
                //exp0.tif
                int numberOfIndex = 0;
                String fileForBox = path+lang+font+"exp"+numberOfIndex+".tif";
                FileUtils.copyfiles(inputFilename, fileForBox) ;//renameTo(new File(fileForBox));
                String boxFileName = TesseractUtils.createBoxFile(fileForBox);
                //read boxfile  
                //String boxFileNameWithNoBox = new File(inputFilename).getParent()+File.separatorChar+FileUtils.getFilenameNoExt(new File(inputFilename));
                List boxData  = TesseractUtils.readBoxFile(boxFileName);
                
                tco.findCharDiff();//find char diffs.
                //correct box file.
                for(int i = 0 ; i < tco.getCharListDiffs().size();i++){
                    Word wT = (Word)tco.getCharListDiffs().get(i);
                    int position  = wT.getStartIndex();
                    System.out.println("box correct p:"+position+",oldText:"+wT.getOldText()+",newText:"+wT.getText());
                    ((String[])boxData.get(position))[0]=wT.getText();
                }
                //rename box file.
                File frename = new File(boxFileName); frename.renameTo(new File(path+"old_box"));
                
                TesseractUtils.saveBoxFile(boxFileName, boxData);
            }
        
        }//ok for train
        else {
            System.out.println("File has lating letters");
        }
       
    }

    public static void updateConfigFiles(HashMap data) throws IOException{
        String currentTrainPath = (String)data.get("currentTrainPath");
        String[] filenameArray = (String[])data.get("inputfiles");
        for(int i = 0 ; i < filenameArray.length;i++){
            String outputfile = TesseractUtils.createTrainData(filenameArray[i]);//REQ35: Create Train data
        }
        String[] boxFilesArray = (String[])data.get("boxFiles");
        boolean extractUnicharFile = (Boolean)data.get("extractUnichar");
        //compute character set. REQ36:Compute the Character Set
        //unicharset_extractor ell.verdana.exp0.box ell.verdana.exp1.box ell.verdana.exp2.box ell.verdana.exp3.box ell.verdana.exp4.box ell.verdana.exp5.box ell.verdana.exp6.box ell.verdana.exp7.box ell.verdana.exp8.box ell.verdana.exp9.box ell.verdana.exp10.box ell.verdana.exp11.box ell.verdana.exp12.box;
        if(extractUnicharFile){
            TesseractUtils.extractUnichar(boxFilesArray);
        }
        else{//i have unichar file. copy to train folder.
            String unicharFile = (String)data.get("unicharfile");
            FileUtils.copyfiles(unicharFile, currentTrainPath+"unicharset");
        }
        /*font_properties (new in 3.01)
            <fontname> <italic> <bold> <fixed> <serif> <fraktur>
            timesitalic 1 0 0 1 0*/
        
    }
}
